import Router from '@koa/router';
import logger from '../logger.js';
import response from '../response.js';
import { GetOpenID, getPhoneNumber } from '../common/wx.js';
import lsyPay from '../common/lsyPay.js';
import db from '../mysqlHelper.js';
import moment from 'moment';

import axios from 'axios';
import md5 from 'md5';
import FormData from 'form-data';

const key = '850c5e2068974bd189ba7f238fac7362';
const dockingAccounts = '97b4c1e40022481c8e056da2f726a19f';
const baseUrl = 'http://47.121.25.20';

const packageId_30m = 'c48d26da-b68e-49f7-aadc-67057535043c';

const packageList = [{
    name: '300M流量包',
    id: 'c48d26da-b68e-49f7-aadc-67057535043c'
},
{
    name: '500M流量包',
    id: '3f00e9bf-0edd-493f-b521-d3e3958b5086'

}
]

// 签名生成方式 将接口所需参数存入数组或者Map中按字典顺序排序 转成JSON字符串拼接密钥进行md5加密
function getSign(params) {
    const sortedObj = {};
    Object.keys(params).sort().forEach(key => {
        sortedObj[key] = params[key];
    });
    // console.log(sortedObj);
    let str = JSON.stringify(sortedObj);
    str += key;
    console.log('签名前明文:', str);
    return md5(str);
}
async function getCardInfo(cardNo) {
    let param = {
        cardNo: cardNo,
        type: "1",
        dockingAccounts: dockingAccounts,
        timeStamp: moment().unix().toString(),
    }
    const form = new FormData();
    // 遍历params并添加参数到FormData
    for (const key in param) {
        if (param.hasOwnProperty(key)) {
            form.append(key, param[key]);
        }
    }
    let sign = getSign(param);
    const options = {
        method: 'GET',
        url: `${baseUrl}/java/card/publicApi/getCardInfo`,
        headers: {
            password: sign,
            Accept: '*/*',
            'Accept-Encoding': 'gzip, deflate, br',
            'User-Agent': 'PostmanRuntime-ApipostRuntime/1.1.0',
            Connection: 'keep-alive',
            'content-type': 'multipart/form-data'
        },
        data: form
    };

    try {
        let response = await axios.request(options);
        console.log('获取SIM卡信息:', response.data);
        return response.data;
    }
    catch (error) {
        console.error(error.message);
        throw new Error('获取SIM卡信息失败: ' + error.message);
    }




}
async function editStatus(cardNo, type) {
    let param = {
        cardNo: cardNo,
        type: type,
        dockingAccounts: dockingAccounts,
        timeStamp: moment().unix().toString(),
    }
    const form = new FormData();
    // 遍历params并添加参数到FormData
    for (const key in param) {
        if (param.hasOwnProperty(key)) {
            form.append(key, param[key]);
        }
    }
    let sign = getSign(param);
    console.log('签名:', sign);
    const options = {
        method: 'PUT',
        url: `${baseUrl}/java/card/publicApi/editStatus`,
        headers: {
            password: sign,
            Accept: '*/*',
            'Accept-Encoding': 'gzip, deflate, br',
            'User-Agent': 'PostmanRuntime-ApipostRuntime/1.1.0',
            Connection: 'keep-alive',
            'content-type': 'multipart/form-data'
        },
        data: form
    };
    console.log('编辑SIM卡状态参数:', param);
    try {
        let response = await axios.request(options);
        console.log('编辑SIM卡状态响应:', response.data);
        return response.data;
    } catch (error) {
        console.error(error.message);
        // throw new Error('编辑SIM卡状态失败: ' + error.message);
    }




}
async function orderPackage(cardNo, packageId) {
    let param = {
        cardNo: cardNo,
        packageCode: packageId,
        takeeffectType: "1",
        dockingAccounts: dockingAccounts,
        timeStamp: moment().unix().toString()
    }
    const form = new FormData();
    // 遍历params并添加参数到FormData
    for (const key in param) {
        if (param.hasOwnProperty(key)) {
            form.append(key, param[key]);
        }
    }
    let sign = getSign(param);
    console.log('签名:', sign);
    const options = {
        method: 'post',
        url: `${baseUrl}/java/card/publicApi/orderPackage`,
        headers: {
            password: sign,
            Accept: '*/*',
            'Accept-Encoding': 'gzip, deflate, br',
            'User-Agent': 'PostmanRuntime-ApipostRuntime/1.1.0',
            Connection: 'keep-alive',
            'content-type': 'multipart/form-data'
        },
        data: form
    };

    try {
        let response = await axios.request(options);
        console.log('获取SIM卡信息:', response.data);
        return response.data;
    }
    catch (error) {
        console.error(error.message, `url:${options.url},param:${JSON.stringify(param)}`);
        //  throw new Error('单卡订购失败: ' + error.message, `url:${options.url},param:${JSON.stringify(param)}`);
    }
}

// orderPackage('8986112424808031689', packageId_30m);

// await getCardInfo('8986112424808031689');
// editStatus('8986112424808031689', "1");

//蓝灵珠 SIM卡管理平台对接
const router = new Router();
router.prefix('/api');

//获取可以充值的套餐列表
router.post(`/lnz/getPackageList`, async (ctx) => {
    ctx.body = response.success(packageList);
});

//给卡片订购流量包
router.post(`/lnz/orderPackage`, async (ctx) => {
    let body = ctx.request.body;
    if (body == null) {
        ctx.body = response.fail('参数不允许为空');
        return;
    }
    if (body.cardNo == null) {
        ctx.body = response.fail('缺少必填字段 cardNo');
        return;
    }
    if (body.packageId == null) {
        ctx.body = response.fail('缺少必填字段 packageId');
        return;
    }
    try {
        let res = await orderPackage(body.cardNo, body.packageId);
        ctx.body = res;
    } catch (e) {
        ctx.body = response.fail('订购失败: ' + e.message);
    }
});

router.post(`/lnz/editStatus`, async (ctx) => {
    let body = ctx.request.body;
    if (body == null) {
        ctx.body = response.fail('参数不允许为空');
        return;
    }
    if (body.cardNo == null) {
        ctx.body = response.fail('缺少必填字段 cardNo');
        return;
    }
    if (body.type == null) {
        ctx.body = response.fail('缺少必填字段 type');
        return;
    }
    try {

        let res = await editStatus(body.cardNo, body.type);
        ctx.body = res;
    } catch (e) {
        ctx.body = response.fail('操作失败: ' + e.message);
    }
});

//获取卡片信息
router.post(`/lnz/getCardInfo`, async (ctx) => {
    let body = ctx.request.body;
    if (body == null) {
        ctx.body = response.fail('参数不允许为空');
        return;
    }
    if (body.cardNo == null) {
        ctx.body = response.fail('缺少必填字段 cardNo');
        return;
    }
    try {
        let res = await getCardInfo(body.cardNo);

        ctx.body = res;
    } catch (e) {
        ctx.body = response.fail('获取卡片信息失败: ' + e.message);
    }
});


export { router };


